'''
@since: Jan 6, 2012
@author: Chris Giacofei
'''
from xml.etree import ElementTree as ET
from xml.dom import minidom

def prettify(elem):
    """Return a pretty-printed XML string for the Element.
    """
    rough_string = ET.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="  ")

def add_line(root, entry):
    
    line_item = ET.SubElement(root, 'log_line')
    
    for key in entry.keys():
        ET.SubElement(line_item, key).text = str(entry[key])

    return root

def write_log(entry, filename):

    try:
        root = ET.parse(filename).getroot()
    except:
        print('No file found, creating new.')
        root = ET.Element('Log')
        
    for line in entry:   
        new_xml = add_line(root, line)
        
    new_xml = prettify(new_xml)
    print(new_xml)
    xml_file = open(filename, 'w')
    xml_file.write(new_xml)
    #ET.ElementTree(new_xml).write(filename)

